import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/internal/Observable';
import { throwError } from 'rxjs/internal/observable/throwError';
import { delay, catchError } from 'rxjs/operators';

import { environment as env } from 'src/environments/environment';

@Injectable({
  providedIn: 'root'
})
export class MockApiService {

  constructor(private httpClient: HttpClient) { }

  fetch(url): Observable<any> {
    return this.httpClient.get(this.getBaseUrl() + env.jsonUrl + url)
      .pipe(
        delay(100),
        catchError(this.handleError)
      );
  }

  private getBaseUrl() {
    return `${location.protocol}//${location.hostname + (location.port ? ':' + location.port : '')}/`;
  }

  private handleError(error: any) {
    const errorMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server error';

      return throwError(error.error);
  }

}
